//
//  CommonAction.m
//  quxiangtao
//
//  Created by xbmios on 2018/8/14.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "CommonAction.h"
#import <AlibcTradeBiz/AlibcTradeBiz.h>
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import "JTNavigationController.h"

#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>

#import "UserInfoModel.h"

#import <AlipaySDK/AlipaySDK.h>
#import "APOrderInfo.h"

#import "BindThirdPartAuthViewController.h"

@implementation CommonAction

+ (CommonAction *)sharedInstance {
    
    static CommonAction *instance;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    
    });
    
    return instance;
}

#pragma mark -判断用户是否登录
- (BOOL)isLoginWithParentVc:(UIViewController *)parentVC {
    
    if (![CommonUserInfo sharedInstance].isLogin) {
        // 未登录
        NSLog(@"未登录");
        
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        
        JTNavigationController *nav = [[JTNavigationController alloc] initWithRootViewController:loginVC];
        
        [parentVC presentViewController:nav animated:YES completion:nil];
        
        return NO;
        
    }else {
        // 已登录
        NSLog(@"已登录");
        
        return YES;
        
    }
    
}

#pragma mark -获取用户信息
- (void)getUserInfoWithBlock:(DlReturnBlock)result {
    
    if ([CommonUserInfo sharedInstance].isLogin) {
        
        NSString *str = [NSString stringWithFormat:@"{\"user_mobile\" : \"%@\"}", [RSA encryptString:[CommonUserInfo sharedInstance].phone publicKey:PublicKey]];
        
        [UserInfoModel getUserInfoWithPar:str succes:^(id responseObject) {
            
            if (result) {
                
                result(responseObject);
                
            }
            
            
        } failBlock:^(NSError *error) {
            
            if (error) {
                
                NSLog(@"error:%@", error);
                [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
            
            }
            
        }];
        
    }
    
}

#pragma mark -手淘/天猫首次授权登录 并跳转对应商品的详情页
- (void)authWithViewController:(UIViewController *)vc andItemDetailPage:(NSString *)itemDetailPage {
    
    if(![[ALBBSession sharedInstance] isLogin]) {

        // 授权登录
        [[ALBBSDK sharedInstance] auth:vc successCallback:^(ALBBSession *session) {
            NSString *tip = [NSString stringWithFormat:@"登录的用户信息:%@",[session getUser]];
            ALBBUser *user = [session getUser];
             NSLog(@"%@\n淘宝授权获得信息:\n%@", [tip description], user.openId);
            [self tbAuthWihUser:user andVC:vc];
        } failureCallback:^(ALBBSession *session, NSError *error) {
            NSString *tip = [NSString stringWithFormat:@"登录失败:%@",@""];
            NSLog(@"%@", tip);
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:@"授权登录失败，请重试"];
            
        }];
        
    }else {
        
        ALBBSession *session = [ALBBSession sharedInstance];
        NSString *tip = [NSString stringWithFormat:@"登录的用户信息:%@",[[session getUser] ALBBUserDescription]];
        
        ALBBUser *user = [session getUser];
        
        NSLog(@"%@\n淘宝授权获得信息:\n%@", tip, user.openId);
        
        [self tbAuthWihUser:user andVC:vc];


    }
    
    // 退出登录
//    [[ALBBSDK sharedInstance] logout];
    
}

- (void)tbAuthWihUser:(ALBBUser *)user andVC:(UIViewController *)parentVC {
    
    NSString *str = [NSString stringWithFormat:@"{\"openId\" : \"%@\"}", [RSA encryptString:user.openId publicKey:PublicKey]];
    
    [PPNetworkHelper POST:@"user/login/empower" parameters:@{@"json" : str} success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            [CommonUserInfo sharedInstance].isLogin = YES;
            [CommonUserInfo sharedInstance].phone = [[NSString alloc] initWithFormat:@"%@", responseObject[@"data"][@"user_mobile"]];
            [CommonUserInfo sharedInstance].user_id = [[NSString alloc] initWithFormat:@"%@", responseObject[@"data"][@"user_id"]];
            
            [CommonUserInfo sharedInstance].nickName = [[NSString alloc] initWithFormat:@"%@", responseObject[@"data"][@"user_name"]];
            [parentVC dismissViewControllerAnimated:YES completion:nil];
            // 已绑定手机号
//            UIWindow *window = [UIApplication sharedApplication].keyWindow;
//            window.backgroundColor = WhiteColor;
//            window.rootViewController = [BaseTabbarViewController sharedMainTabBarVC];
            
        }else if ([responseObject[@"code"] integerValue] == 2){
            
            // 未绑定手机号
            BindThirdPartAuthViewController *vc = [[BindThirdPartAuthViewController alloc] init];
            vc.title = @"绑定手机号";
            vc.nick_name = user.nick;
            vc.photo_url = user.avatarUrl;
            vc.openID = user.openId;

            JTNavigationController *nav = [[JTNavigationController alloc] initWithRootViewController:vc];
            
            [parentVC presentViewController:nav animated:YES completion:nil];
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        
        }
        
    } failure:^(NSError *error) {
    
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
}

#pragma mark -授权登录后跳转淘宝详情页（优惠券）
- (void)goToTbGoodsDetailWith:(UIViewController *)vc itemDetailPage:(NSString *)itemDetailPage {
    
    if (itemDetailPage.length > 0 || ![itemDetailPage isKindOfClass:[NSNull class]]) {
        
        // 商品详情页
//        id<AlibcTradePage> page = [AlibcTradePageFactory itemDetailPage:itemDetailPage];
        
        id<AlibcTradePage> page = [AlibcTradePageFactory requestPage:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:itemDetailPage]]];
        [self OpenByPage:page wihtVC:vc andOpenType:AlibcOpenTypeNative];

    }
    
}

#pragma mark -淘宝 购物车/订单列表
- (void)showCartOrOrderListWith:(UIViewController *)vc {
    
    // 如果没有授权，会自动调用授权界面

    // 淘宝我的订单页面 全部
    id<AlibcTradePage> page = [AlibcTradePageFactory myOrdersPage:0 isAllOrder:YES];

    [self OpenByPage:page wihtVC:vc andOpenType:AlibcOpenTypeH5];
    
}

- (void)showCartListWithVC:(UIViewController *)vc {
    
     id<AlibcTradePage> page = [AlibcTradePageFactory myCartsPage];

    [self OpenByPage:page wihtVC:vc andOpenType:AlibcOpenTypeH5];
    
    
}

- (void)OpenByPage:(id<AlibcTradePage>)page wihtVC:(UIViewController *)vc andOpenType:(AlibcOpenType)openType
{
    AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];

    showParam.openType = openType;
    showParam.backUrl = @"tbopen25027070";
    
    // 优先拉起手淘：@"taobao_scheme" \\\ 天猫：tmall_scheme
    showParam.linkKey = self.linkType;
    showParam.isNeedPush = YES;
    showParam.nativeFailMode = AlibcNativeFailModeJumpH5;

    NSInteger res = [[AlibcTradeSDK sharedInstance].tradeService show:vc.navigationController page:page showParams:showParam taoKeParams:nil trackParam:nil tradeProcessSuccessCallback:^(AlibcTradeResult * _Nullable result) {
        
        if (result.result == AlibcTradeResultTypePaySuccess) {
            NSString *tip = [NSString stringWithFormat:@"交易成功:成功的订单%@\n，失败的订单%@\n",[result payResult].paySuccessOrders,[result payResult].payFailedOrders];
            
            NSLog(@"交易订单：%@",tip);
            
        }else if(result.result==AlibcTradeResultTypeAddCard) {
            
            NSLog(@"加购成功");
            
        }
        
    } tradeProcessFailedCallback:^(NSError * _Nullable error) {
        
        NSLog(@"error%ld", error.code);
        
        /*
         /** 交易链路失败 */
//        AlibcErrorProcessFailed = 3001,
        /** 交易链路中用户取消了操作 */
//        AlibcErrorCancelled = 3002,
        /** 交易链路中发生支付但是支付失败 */
//        AlibcErrorPaymentFailed = 3003,
        /** itemId无效 */
//        AlibcErrorInvalidItemID = 3004,
        /** page url为空 */
//        AlibcErrorNullPageURL = 3005,
        /** shopId无效 */
//        AlibcErrorInvalidShopID = 3006,
//         */
        
        //        退出交易流程
        if (error.code==AlibcErrorCancelled) {
        
            return ;
        
        }
        
        NSDictionary *infor = [error userInfo];
        NSArray *orderid = [infor objectForKey:@"orderIdList"];
        NSString *tip = [NSString stringWithFormat:@"交易失败:\n订单号\n%@",orderid];
//            [[MyAlertView alertViewWithTitle:@"交易失败" message:tip oALinClicked:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]show];
        
        NSLog(@"交易失败");
        
    }];
    
    NSLog(@"%zd",res);
    
}

#pragma mark -友盟分享
/*
 dict 包含内容
 
 @"thumbURL"   : 分享的小图标,
 @"title"     : 标题,
 @"des"        : 分享内容,
 @"webpageUrl" : 分享链接
 
 */
- (void)sharedWithDict:(NSDictionary *)dict withController:(UIViewController *)controller {
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    //    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:]];
    //    UIImage *image = [UIImage imageWithData:data];
    //    UIImage *thumbURL = image; // @"xbmiPhoneSpootlight7_401"
    
    UIImage *thumbURL = [UIImage imageNamed:dict[@"thumbURL"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:dict[@"title"] descr:dict[@"des"] thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = dict[@"webpageUrl"];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_Sina),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
    
    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:controller completion:^(id data, NSError *error) {
            if (error) {
                
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
            
        }];
    }];
    
}

#pragma mark -获取验证码
- (void)getCodeWithPhone:(NSString *)phoneNum type:(NSString *)type andSender:(UIButton *)sender phoneCodeBlock:(PhoneCodeBlock)codeBlock {
    
    if ([phoneNum length] <= 0) {
        
        NSLog(@"请输入手机号");
        [[KYAlertView sharedInstance] showAlertViewWithMessage:@"请输入手机号码"];
        
        return ;
        
    }
    
    if (phoneNum.length > 11) {
        
        NSLog(@"请输入正确手机号码");
        [[KYAlertView sharedInstance] showAlertViewWithMessage:@"请输入正确手机号码"];
        
        return ;
        
    }
    
    [self receiveCheckNumButton:sender];
    
    NSString *par = [NSString stringWithFormat:@"{\"user_mobile\":\"%@\", \"type\":\"%@\"}", [RSA encryptString:phoneNum publicKey:PublicKey], [RSA encryptString:type publicKey:PublicKey]];
    
    [PPNetworkHelper POST:@"qxtcode/scode/scode" parameters:@{@"json" : par} success:^(id responseObject) {
        
        NSLog(@"获取验证码%@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if ([[responseObject allKeys] containsObject:@"data"]) {
                
                NSDictionary *dict = responseObject[@"data"];
                
                if (codeBlock) {
                    
                    if ([[dict allKeys] containsObject:@"code"]) {
                        
                        codeBlock(dict[@"code"]);
                        
                    }
                    
                }
                
            }
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
      
        }
        
    } failure:^(NSError *error) {
        
        if (error) {
            
            NSLog(@"%@", error);
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
            
        }
        
    }];
    
}

#pragma mark -验证码倒计时
- (void)receiveCheckNumButton:(UIButton *)sender {
    
    __block int timeout = 60;//倒计时时间
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){//倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示根据自己需求设置
                [sender setTitle:@"重新获取"forState:UIControlStateNormal];
                [sender setTitleColor:Color333333 forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
//                sender.backgroundColor = [UIColor grayColor];
                [sender setTitleColor:Colordddddd forState:UIControlStateNormal];
                sender.userInteractionEnabled = NO;
                //设置界面的按钮显示根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [sender setTitle:[NSString stringWithFormat:@"%@s后重试",strTime]forState:UIControlStateNormal];
                [UIView commitAnimations];
                
                sender.userInteractionEnabled = NO;
            
            });
            
            timeout--;
        }
        
    });
    
    dispatch_resume(_timer);
    
}

#pragma mark -提示弹框
- (void)alertViewWith:(NSString *)title description:(NSString *)des andBtns:(NSArray *)btnArr withParentVC:(UIViewController *)parentVC {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:des preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
    }];
    
    [alert addAction:confirmAction];
    [alert addAction:cancleAction];
    [parentVC presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark -支付宝支付
- (void)goAlipayWithRsa2PrivateKey:(NSString *)privateKey ReturnBlock:(DlReturnBlock)result {
    
//    NSString *appScheme = @"qxt2018082961163803";
    NSString *appScheme = AliPayAppid;

    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:privateKey fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        if ([resultDic[@"resultStatus"] integerValue] == 9000) {
            if (result) {
                result(@"");
            }
        }
    }];
}


#pragma mark -支付接口
- (void)gotoPay:(NSString *)par type:(NSInteger)type andReturnBlock:(DlReturnBlock)result {
    
    NSString *str = par;
    
    NSString *url = @"";
    
    if (type == 1) {
        //注释是赵东亮写的
        //url = @"pay/wcpay/alipay";
        
         url = @"bargain/Buy/index";
        
    }else {
        
        url = @"bargain/Buy/index";
    }
    
    [PPNetworkHelper POST:url parameters:@{@"json" : str} success:^(id responseObject) {
        
        NSLog(@"支付接口：%@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            [self goAlipayWithRsa2PrivateKey:responseObject[@"data"] ReturnBlock:result];
        }else {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        
    } failure:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
}

#pragma mark -初始化接口（用户访问记录）
// route : 页面信息
- (void)userVisitRecordWithRoute:(NSString *)routeStr {
    
    NSString *user_id = [RSA encryptString:[NSString stringWithFormat:@"%@", [CommonUserInfo sharedInstance].user_id] publicKey:PublicKey];
    NSString *route = [RSA encryptString:routeStr publicKey:PublicKey];
    NSString *device = [RSA encryptString:[DLayout phoneVersion] publicKey:PublicKey];
    
    NSString *str = [NSString stringWithFormat:@"{\"user_id\" : \"%@\", \"route\" : \"%@\", \"device\" : \"%@\"}", user_id, route, device];
    
    [PPNetworkHelper POST:@"user/Statistics/count" parameters:@{@"json" : str} success:^(id responseObject) {
        
        NSLog(@"用户访问记录接口%@", responseObject);
        
    } failure:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
        
    }];
    
}

@end
